<template>
  <div class="reconciliation-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="客户ID">
          <el-input v-model="searchForm.customerId" placeholder="请输入客户ID" clearable />
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker
            v-model="searchForm.startDate"
            type="date"
            placeholder="请选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="searchForm.endDate"
            type="date"
            placeholder="请选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">总交易笔数</div>
            <div class="stats-value">{{ stats.totalTransactions || 0 }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">应收金额</div>
            <div class="stats-value">¥{{ stats.totalReceivable || '0.00' }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">已收金额</div>
            <div class="stats-value">¥{{ stats.totalReceived || '0.00' }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-title">未收金额</div>
            <div class="stats-value">¥{{ stats.totalUnpaid || '0.00' }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-card class="action-card">
      <el-button type="warning" @click="handleExport">导出对账报表</el-button>
      <el-button type="info" @click="handleRefresh">刷新数据</el-button>
    </el-card>

    <!-- 对账结果 -->
    <el-card class="table-card">
    

      <!-- 对账数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
      >
        <el-table-column prop="customerId" label="客户ID" width="100" />
        <el-table-column prop="customerName" label="客户名称" width="200" />
        <el-table-column prop="orderNo" label="订单编号" width="150" />
        <el-table-column prop="orderDate" label="订单日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.orderDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="orderAmount" label="订单金额" width="120">
          <template #default="{ row }">
            ¥{{ row.orderAmount || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="paidAmount" label="已收金额" width="120">
          <template #default="{ row }">
            ¥{{ row.paidAmount || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="unpaidAmount" label="未收金额" width="120">
          <template #default="{ row }">
            ¥{{ row.unpaidAmount || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 对账详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="对账详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="客户ID">{{ detailData.customerId }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ detailData.customerName }}</el-descriptions-item>
        <el-descriptions-item label="订单编号">{{ detailData.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="订单日期">{{ formatDate(detailData.orderDate) }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">¥{{ detailData.orderAmount || '0.00' }}</el-descriptions-item>
        <el-descriptions-item label="已收金额">¥{{ detailData.paidAmount || '0.00' }}</el-descriptions-item>
        <el-descriptions-item label="未收金额">¥{{ detailData.unpaidAmount || '0.00' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(detailData.status)">
            {{ getStatusText(detailData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailData.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reconciliationApi } from '@/api/crm/reconciliation'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const stats = reactive({
  totalTransactions: 0,
  totalReceivable: '0.00',
  totalReceived: '0.00',
  totalUnpaid: '0.00'
})

// 搜索表单
const searchForm = reactive({
  customerId: '',
  startDate: '',
  endDate: ''
})

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框相关
const detailDialogVisible = ref(false)
const detailData = reactive({})

// 获取数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      ...searchForm
    }
    
    const response = await reconciliationApi.getReconciliation(params)
    
    if (response && response.code === 200 && response.data) {
      // 这里可以根据实际业务需求处理数据
      // 目前使用模拟数据
      tableData.value = generateMockData()
      pagination.total = tableData.value.length
      calculateStats()
    } else {
      console.error('API返回错误:', response)
      ElMessage.error('获取对账数据失败：数据格式不正确')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取对账数据失败:', error)
    ElMessage.error('获取数据失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 生成模拟数据（实际项目中应该从后端获取）
const generateMockData = () => {
  return [
    {
      customerId: 'C001',
      customerName: '示例客户1',
      orderNo: 'ORD202501001',
      orderDate: '2025-01-15',
      orderAmount: 15000.00,
      paidAmount: 12000.00,
      unpaidAmount: 3000.00,
      status: 'partial',
      remark: '部分收款'
    },
    {
      customerId: 'C002',
      customerName: '示例客户2',
      orderNo: 'ORD202501002',
      orderDate: '2025-01-16',
      orderAmount: 8000.00,
      paidAmount: 8000.00,
      unpaidAmount: 0.00,
      status: 'paid',
      remark: '已全额收款'
    },
    {
      customerId: 'C003',
      customerName: '示例客户3',
      orderNo: 'ORD202501003',
      orderDate: '2025-01-17',
      orderAmount: 25000.00,
      paidAmount: 0.00,
      unpaidAmount: 25000.00,
      status: 'unpaid',
      remark: '未收款'
    }
  ]
}

// 计算统计数据
const calculateStats = () => {
  const data = tableData.value
  stats.totalTransactions = data.length
  stats.totalReceivable = data.reduce((sum, item) => sum + (item.orderAmount || 0), 0).toFixed(2)
  stats.totalReceived = data.reduce((sum, item) => sum + (item.paidAmount || 0), 0).toFixed(2)
  stats.totalUnpaid = data.reduce((sum, item) => sum + (item.unpaidAmount || 0), 0).toFixed(2)
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    customerId: '',
    startDate: '',
    endDate: ''
  })
  pagination.current = 1
  loadData()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

// 刷新数据
const handleRefresh = () => {
  loadData()
}

// 查看详情
const handleViewDetail = (row) => {
  Object.assign(detailData, row)
  detailDialogVisible.value = true
}

// 导出
const handleExport = async () => {
  try {
    if (!tableData.value || tableData.value.length === 0) {
      ElMessage.warning('暂无数据可导出，请先查询数据')
      return
    }
    
    ElMessage.info('正在导出对账报表，请稍候...')
    
    // 准备CSV数据
    const headers = ['客户ID', '客户名称', '订单编号', '订单日期', '订单金额', '已收金额', '未收金额', '状态', '备注']
    const dataList = []
    
    // 添加数据行
    tableData.value.forEach(row => {
      dataList.push([
        row.customerId || '',
        row.customerName || '',
        row.orderNo || '',
        formatDate(row.orderDate),
        row.orderAmount || '0.00',
        row.paidAmount || '0.00',
        row.unpaidAmount || '0.00',
        getStatusText(row.status),
        row.remark || ''
      ])
    })
    
    // 添加汇总行
    dataList.push([
      '总计',
      '',
      '',
      '',
      `¥${stats.totalReceivable}`,
      `¥${stats.totalReceived}`,
      `¥${stats.totalUnpaid}`,
      `记录数: ${stats.totalTransactions}`,
      ''
    ])
    
    // 创建CSV文件并下载
    const workbook = new Blob([
      '\uFEFF' + // BOM for UTF-8
      headers.join(',') + '\n' +
      dataList.map(row => row.join(',')).join('\n')
    ], { type: 'text/csv;charset=utf-8;' })
    
    const url = window.URL.createObjectURL(workbook)
    const link = document.createElement('a')
    link.href = url
    link.download = `客户对账报表_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败：' + error.message)
  }
}

// 工具函数
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  if (isNaN(d)) return String(date).slice(0, 10)
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

const getStatusType = (status) => {
  const statusMap = {
    'paid': 'success',
    'partial': 'warning',
    'unpaid': 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    'paid': '已收款',
    'partial': '部分收款',
    'unpaid': '未收款'
  }
  return statusMap[status] || '未知'
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.reconciliation-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-item {
  padding: 10px;
}

.stats-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.action-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
